package com.ada.shorurl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class Base512Converter {
    private static final String CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";
    private static final int BASE = CHARACTERS.length();

    public static BigInteger base512ToBase10(String base512) {
        BigInteger base10 = BigInteger.ZERO;
        BigInteger multiplier = BigInteger.ONE;

        for (int i = base512.length() - 1; i >= 0; i--) {
            char c = base512.charAt(i);
            int digit = CHARACTERS.indexOf(c);
            BigInteger digitValue = BigInteger.valueOf(digit);
            BigInteger term = digitValue.multiply(multiplier);
            base10 = base10.add(term);
            multiplier = multiplier.multiply(BigInteger.valueOf(BASE));
        }

        return base10;
    }
    public static BigInteger base512ToBase10a(String base512) {
        BigInteger base10 = BigInteger.ZERO;
        int power = 0;

        for (int i = base512.length() - 1; i >= 0; i--) {
            int digit = CHARACTERS.indexOf(base512.charAt(i));
            BigInteger value = BigInteger.valueOf(digit);
            BigInteger weightedValue = value.multiply(BigInteger.valueOf(512).pow(power));
            base10 = base10.add(weightedValue);
            power++;
        }

        return base10;
    }
    public static String base10ToBase512(long base10) {
        List<Integer> digits = new ArrayList<>();

        while (base10 > 0) {
            int remainder = (int) (base10 % BASE);
            digits.add(remainder);
            base10 /= BASE;
        }

        StringBuilder base512 = new StringBuilder();

        for (int i = digits.size() - 1; i >= 0; i--) {
            base512.append(CHARACTERS.charAt(digits.get(i)));
        }

        return base512.toString();
    }
    public static void main(String[] args) {
        String base512 = "abcdefg";
        BigInteger base10 = base512ToBase10(base512);
        System.out.println(base10ToBase512(base10.longValue()));
        System.out.println("Base512: " + base512);
        System.out.println("Base10: " + base10);
    }
}
